package com.zw.yzk.kabu.data.repository;

import com.zw.yzk.kabu.data.network.task.Task;
import com.zw.yzk.kabu.data.cache.db.DataBaseManager;
import com.zw.yzk.kabu.data.cache.db.User;
import com.zw.yzk.kabu.data.cache.store.UserStore;
import com.zw.yzk.kabu.data.constant.Constant;
import com.zw.yzk.kabu.data.network.ServiceGenerator;
import com.zw.yzk.kabu.data.network.entity.FansListEntity;
import com.zw.yzk.kabu.data.network.service.FansListService;
import com.zw.yzk.kabu.data.network.task.GetFansTask;

import javax.inject.Inject;

import rx.Observable;
import rx.functions.Func1;

/**
 * Created by zhanwei on 2017/1/12.
 */

public class FansListRepository extends CommonRepository {

    private int totalCount;

    @Inject
    public FansListRepository() {
        totalCount = GetFansTask.DEFAULT_FANS_COUNT_PER_PAGE;
    }


    @Override
    protected Observable connectServer(Task task) {
        FansListService service = ServiceGenerator.createService(FansListService.class);
        GetFansTask getFansTask = (GetFansTask) addToken(task);

        if (getFansTask.start >= totalCount) {
            FansListEntity entity = new FansListEntity();
            //已经全部加载，直接返回空列表
            entity.errCode = Constant.RESULT_OK;
            entity.result.total = totalCount;

            return Observable.just(entity);
        } else {
            return service.getFansList(
                    getFansTask.ownerId,
                    getFansTask.userId,
                    getFansTask.accessToken,
                    getFansTask.start,
                    getFansTask.size);
        }
    }

    @Override
    protected Func1<FansListEntity, Observable> getServerData() {
        return new Func1<FansListEntity, Observable>() {
            @Override
            public Observable call(FansListEntity entity) {
                totalCount = entity.result.total;
                updateUser(entity);
                return Observable.just(entity);
            }
        };
    }

    /**
     * 更新user信息
     *
     * @param entity
     */
    private void updateUser(FansListEntity entity) {
        User user = DataBaseManager.getInstance().getLoginUser();
        if(user == null) {
            return;
        }
        user.setTotalFans(entity.result.total);
        new UserStore().updateUserInfo(user);
    }
}
